<?php

namespace addon\ly_shareholder\app\service\core;

use addon\ly_shareholder\app\dict\shareholder\ShareholderDict;
use addon\ly_shareholder\app\model\Shareholder;
use addon\ly_shareholder\app\model\ShareholderLevel;
use addon\shop\app\dict\order\OrderDict;
use addon\shop\app\model\order\Order;
use app\model\member\Member;
use core\base\BaseCoreService;
use core\exception\CommonException;
use think\Model;
use think\facade\Db;
use think\facade\Log;

/**
 * 股东
 */
class CoreShareholderService extends BaseCoreService
{

    public function __construct()
    {
        parent::__construct();
        $this->model = new Shareholder();
    }

    /**
     * 查询股东(有效的)
     * @param $site_id
     * @param $member_id
     * @return Shareholder|array|mixed|Model
     */
    public function findOfAction($site_id, $member_id)
    {
        return $this->model->where(
            [
                ['site_id', '=', $site_id],
                ['member_id', '=', $member_id],
                ['status', '=', ShareholderDict::NORMAL]
            ]
        )->findOrEmpty();
    }

    /**
     * 添加股东
     * @param $site_id
     * @param $member_id
     * @return true
     */

    public function add($site_id, $member_id, $level_id)
    {

         $level = (new ShareholderLevel())::where(['site_id' => $site_id, 'level_id' => $level_id])->findOrEmpty();

        if ($level->isEmpty()) throw new CommonException('LY_SHAREHOLDER_PLEASE_SELECT_SHAREHOLDER_LEVEL');

        //判断股东是否是否是有效的会员
        $member = (new Member())->where([['site_id', '=', $site_id], ['member_id', '=', $member_id]])->findOrEmpty();
        if($member->isEmpty()) throw new CommonException('LY_SHAREHOLDER_PLEASE_SELECT_MEMBER');

        $shareholder = (new Shareholder())->where([['site_id', '=', $site_id], ['member_id', '=', $member_id]])->findOrEmpty();
        if(!$shareholder->isEmpty()) throw new CommonException('LY_SHAREHOLDER_ALREADY_SHAREHOLDER');
 

        //增加股东
        $insert_data = [
            'site_id' => $site_id,
            'member_id' => $member_id,
            'level_id' => $level_id,
            'shareholder_no' => "NO" . (100000 + $member_id),
            'status' => ShareholderDict::NORMAL,
        ];
        $this->model->create($insert_data);
    }

    /**
     * @param $site_id
     * @param $member_id
     */
    public function find($site_id, $member_id)
    {
        return $this->model->where([['site_id', '=', $site_id], ['member_id', '=', $member_id]])->findOrEmpty();
    }


    /**
     * 累增股东相关分红数据
     * @param int $site_id
     * @param int $member_id
     * @param int|float $number
     * @param string $type
     * @return true
     */
    public function incFenhong(int $site_id, int $member_id, int|float $number, string $type)
    {
        $data = [];
        switch ($type) {
            case 'shareholder_fenhong':
                $data['amount'] = Db::raw('amount + ' . $number);
                // $data['amount_get'] = Db::raw('amount_get + ?', [$number]);
                break;     
        }
        if (!empty($data)) {
            (new Shareholder())->where([['site_id', '=', $site_id], ['member_id', '=', $member_id]])->update($data);
        }
        return true;
    }

    /**
     * 累减股东相关分红数据
     * @param int $site_id
     * @param int $member_id
     * @param int|float $number
     * @param string $type
     * @return true
     */
    public function minFenhong(int $site_id, int $member_id, int|float $number, string $type){
        
        $data = [];
        switch ($type) {
            case 'shareholder_tixian':
                $data['amount_cash_outing'] = Db::raw('amount_cash_outing - ? $number ' );
                break;
        }
        
        if (!empty($data)) {
            (new Shareholder())->where([['site_id', '=', $site_id], ['member_id', '=', $member_id]])->update($data);
        }
        
        return true;
    }


    /**
     * 获取会员的直接下级和二级下级数量，以及特定等级的下级数量
     * @param int $site_id 站点ID
     * @param int $member_id 会员ID
     * @param array|null $level_condition 等级条件，格式为 ['level_id' => 等级ID, 'level_num' => 需要达到的人数]
     * @return array 包含下级数量和特定等级下级人数的数组
     */
    public function getChildNum($site_id, $member_id, $level_condition = null){
        // 获取直接下级会员ID列表
        $child_mids = (new Member())->where([['site_id', '=', $site_id], ['pid', '=', $member_id]])->column('member_id');
        
        // 直接查询下级数量
        $child_num = count($child_mids);
        
        // 如果没有直接下级，直接返回结果
        if (empty($child_mids)) {
            return ['child_num' => 0, 'child2_num' => 0, 'match_level_num' => 0];
        }
        
        // 查询二级下级
        $child2_mids = (new Member())->where([
            ['site_id', '=', $site_id], 
            ['pid', 'in', $child_mids]
        ])->column('member_id');
        $child2_num = count($child2_mids);
        
        // 统计结果
        $result = ['child_num' => $child_num, 'child2_num' => $child2_num];
        
        // 如果需要统计特定等级的下级数量
        if (is_array($level_condition) && !empty($level_condition)) {
            // 处理包含多个条件的数组情况 [{"level_id":2,"level_num":"1"}]
            Log::write('-----ly_shareholder----处理level_condition数组: ' . json_encode($level_condition));
            
            // 初始化标记，默认为true（所有条件都满足）
            $all_conditions_met = true;
            
            foreach ($level_condition as $condition) {
                if (isset($condition['level_id'])) {
                    $level_id = $condition['level_id'];
                    
                    // 查询直接下级中达到指定等级的人数
                    $match_level_num = (new Shareholder())
                        ->where([
                            ['site_id', '=', $site_id], 
                            ['member_id', 'in', $child_mids],
                            ['level_id', '=', $level_id],
                            ['status', '=', ShareholderDict::NORMAL]
                        ])
                        ->count();
                    
                    Log::write([
                        'level_id' => $level_id,
                        'match_level_num' => $match_level_num,
                        'required_num' => $condition['level_num'] ?? 0
                    ]);
                    
                    // 判断该条件是否满足
                    $condition_met = false;
                    if (isset($condition['level_num']) && $match_level_num >= intval($condition['level_num'])) {
                        $condition_met = true;
                    }
                    
                    // 如果有任一条件不满足，则整体不满足
                    if (!$condition_met) {
                        $all_conditions_met = false;
                    }
                }
            }
            
            // 设置第一个条件的匹配数量作为结果（用于显示）
            if (!empty($level_condition[0]) && isset($level_condition[0]['level_id'])) {
                $first_level_id = $level_condition[0]['level_id'];
                $first_match_num = (new Shareholder())
                    ->where([
                        ['site_id', '=', $site_id], 
                        ['member_id', 'in', $child_mids],
                        ['level_id', '=', $first_level_id],
                        ['status', '=', ShareholderDict::NORMAL]
                    ])
                    ->count();
                $result['match_level_num'] = $first_match_num;
            }
            
            $result['can_upgrade'] = $all_conditions_met;
            Log::write('-----ly_shareholder----level_condition数组处理结果: ' . ($all_conditions_met ? 'true' : 'false'));
        }
        
        return $result;
    }

    
    /**
     * 更新会员的团队人数及分红权益
     * @param int $site_id 站点ID
     * @param int $member_id 会员ID
     * @param int $max_level 最大递归层级
     * @param int $current_level 当前递归层级
     * @return int 团队人数
     */
    public function updateTeamCount($site_id, $member_id, $max_level = 10, $current_level = 1){
        // 获取会员信息
        $member = (new Member())->where([['site_id', '=', $site_id], ['member_id', '=', $member_id]])->findOrEmpty();
        if($member->isEmpty()) {
            return 0;
        }
        
        // 如果有上级且未超过最大层级限制，则递归更新上级的团队人数
        if(!empty($member['pid']) && $current_level <= $max_level) {
            $parent_id = $member['pid'];
            // 更新上级股东的团队人数
            $shareholder_parent = $this->model->where([['site_id', '=', $site_id], ['member_id', '=', $parent_id]])->findOrEmpty();
            if(!$shareholder_parent->isEmpty()) {
                // 团队人数+1
                $data = [
                    'team_count' => ['inc', 1], //增加直推团长总人数字段值
                ];
                $this->model->where([['site_id', '=', $site_id], ['member_id', '=', $parent_id]])
                    ->update($data);
                
                // 更新分红权益
                $this->updateRightNum($site_id, $parent_id);
                
                // 记录日志
                Log::write('-----ly_shareholder----更新团队人数: 会员ID=' . $parent_id . ', 层级=' . $current_level);
            }
            
            // 递归更新上级的上级
            $this->updateTeamCount($site_id, $parent_id, $max_level, $current_level + 1);
        }
        
        return 1; // 返回新增的团队人数
    }
    
    /**
     * 更新会员的分红权益数
     * @param int $site_id 站点ID
     * @param int $member_id 会员ID
     * @return bool
     */
    private function updateRightNum($site_id, $member_id) {
        // 获取股东配置
        $config = (new CoreConfigService())->getShareholderConfig($site_id);
        
        // 判断是否开启分红权益
        if($config['fenhong_right'] != '1') {
            return false;
        }
        
        // 获取设置的团队增加人数和权益数
        $team_num = intval($config['team_num']);
        $right_num = intval($config['right_num']);
        
        // 如果配置为0，不进行更新
        if($team_num <= 0 || $right_num <= 0) {
            return false;
        }
        
        // 获取当前股东信息
        $shareholder = $this->model->where([['site_id', '=', $site_id], ['member_id', '=', $member_id]])->findOrEmpty();
        if($shareholder->isEmpty()) {
            return false;
        }
        
        // 计算应有的分红权益数
        $team_count = $shareholder['team_count'];
        $new_right_num = intval($team_count / $team_num) * $right_num;
        
        // 更新分红权益数
        $this->model->where([['site_id', '=', $site_id], ['member_id', '=', $member_id]])
            ->update(['right_num' => $new_right_num]);
        
        // 记录日志
        Log::write('-----ly_shareholder----更新分红权益数: 会员ID=' . $member_id . ', 团队人数=' . $team_count . ', 新权益数=' . $new_right_num);
        
        return true;
    }
}
